<template>
  <div class="update-avatar-container">
    <el-row :gutter="10">
      <el-col :lg="8">
        <div class="left flex-center">
          <el-avatar :src="defaultAvatar" class="avatar-preview">
          </el-avatar>
        </div>
      </el-col>
      <el-col :lg="16">
        <div class="right">
          <vue-cropper
            ref="$cropper"
            :aspect-ratio="1"
            :src="cropperImg"
            class="cropper"
            preview=".avatar-preview"
          />
          <el-row :gutter="30">
            <el-col :lg="14">
              <div class="img-option">
                <el-button size="small" type="primary" @click="zoom(0.2)">
                  <div class="flex-center">
                    <el-icon>
                      <plus/>
                    </el-icon>
                  </div>
                </el-button>
                <el-button size="small" type="primary" @click="zoom(-0.2)">
                  <div class="flex-center">
                    <el-icon>
                      <minus/>
                    </el-icon>
                  </div>
                </el-button>
                <el-button size="small" type="primary" @click="rotate(-90)">
                  <div class="flex-center">
                    <el-icon>
                      <refresh-left/>
                    </el-icon>
                  </div>
                </el-button>
                <el-button size="small" type="primary" @click="rotate(90)">
                  <div class="flex-center">
                    <el-icon>
                      <refresh-right/>
                    </el-icon>
                  </div>
                </el-button>
              </div>
            </el-col>
            <el-col :lg="10">
              <div class="other-option">
                <el-upload :before-upload="beforeUpload" :http-request="requestUpload" :show-file-list="false"
                           action="#">
                  <el-button class="select" size="small" type="primary">
                    <div class="flex-center">
                      <el-icon class="icon">
                        <camera/>
                      </el-icon>
                      <div>选择</div>
                    </div>
                  </el-button>
                </el-upload>
                <el-button class="save" size="small" type="primary" @click="uploadImg()">
                  <div class="flex-center">
                    <el-icon class="icon">
                      <upload-filled/>
                    </el-icon>
                    <div>保存</div>
                  </div>
                </el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>

export default {
  name: "Avatar",
}
</script>

<script setup>
import {ref, defineEmits} from 'vue'
import {useStore} from 'vuex'
import {ElMessage} from 'element-plus'
import VueCropper from 'vue-cropperjs'
import 'cropperjs/dist/cropper.css'
import defaultAvatar from '@/assets/defaultAvatar.png'
import {dataURLtoBlob} from '@/commonUtils/dataURLUtils'
// const avatar = ref(null)

const store = useStore()
const avatar = store.state.user.avatar
let cropperImg = ref(avatar)
const $cropper = ref(null)
// 旋转
const rotate = (deg) => {
  $cropper.value.rotate(deg);
}
// 缩放
const zoom = (percent) => {
  $cropper.value.relativeZoom(percent);
}
// 覆盖默认的上传行为
const requestUpload = () => {
}
// 上传预处理
const beforeUpload = (file) => {
  if (file.type.indexOf("image/") === -1) {
    ElMessage({
      type: 'error',
      center: true,
      message: '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。',
    })
  } else {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      cropperImg.value = reader.result
      $cropper.value.replace(cropperImg.value)
    }
  }
}

const emits = defineEmits([
  'uploadSuccess'
])
// 上传图片
const uploadImg = () => {
  const dataURL = $cropper.value.getCroppedCanvas().toDataURL('image/png')
  const dataBlob = dataURLtoBlob(dataURL)
  const formData = new FormData()
  formData.append('avatar', dataBlob, 'avatar.png')
  store.dispatch('user/setUserAvatar', {
    id: store.state.user.id,
    data: formData
  }).then(() => {
    ElMessage({
      type: 'success',
      center: true,
      message: '头像上传成功',
    })
    emits('uploadSuccess')
  }).catch(error => {
    ElMessage({
      type: 'error',
      center: true,
      message: `头像上传失败：${error.message}`,
    })
  })
}

</script>

<style lang="sass" scoped>
.update-avatar-container
  .left
    height: calc(100% - 20px)
    padding-bottom: 20px

    .avatar-preview
      width: 150px
      height: 150px

  .right
    button
      margin: 0

    .cropper
      height: 300px
      margin-bottom: 10px

    .img-option, .other-option
      margin-bottom: 10px
      display: flex
      justify-content: space-around

      .icon
        margin-right: 5px
</style>
